﻿using DotNetty.Buffers;
using DotNetty.Codecs;
using DotNetty.Extensions;
using DotNetty.Transport.Channels;
using System.Text;

var client = new TcpSocketClient("127.0.0.1", 8000);

client.OnChannelPipeline += pipeline =>
{
    //心跳
    //pipeline.AddLast(new IdleStateHandler(5, 0, 0));

    //编码解码器
    pipeline.AddLast(new LengthFieldPrepender(2));
    pipeline.AddLast(new LengthFieldBasedFrameDecoder(ushort.MaxValue, 0, 2, 0, 2));

    pipeline.AddLast(new MyStringDecoder());

    //tls证书
    //var cert = new X509Certificate2(Path.Combine(ExampleHelper.ProcessDirectory, "dotnetty.com.pfx"), "password");
    //var targetHost = cert.GetNameInfo(X509NameType.DnsName, false);
    //pipeline.AddLast(new TlsHandler(stream => new SslStream(stream, true, (sender, certificate, chain, errors) => true), new ClientTlsSettings(targetHost)));

};

client.OnConnecting += () =>
{
    Console.WriteLine("Connecting...");
};

client.OnConnected += async () =>
{
    Console.WriteLine("Connected.");

    var txt = Encoding.UTF8.GetBytes("this is from tcp client message!");
    await client.WriteAndFlushAsync(txt);
};

client.OnMessage += message =>
{
    if (message is IByteBuffer buffer)
    {
        var txt = buffer.ToString(Encoding.UTF8);
        Console.WriteLine($"Message==>{txt}");
    }
    else if (message is string str)
    {
        Console.WriteLine($"Message==>{str}");
    }
};

client.OnException += ex =>
{
    Console.WriteLine($"Exception=>{ex?.Message}");
};

client.OnDisconnected += async () =>
{
    Console.WriteLine("Disconnected.");
    await Task.Delay(2000);
    await client.ConnectAsync(); //reconnect
};

await client.ConnectAsync();

Console.ReadKey();

await client.DisposeAsync();

Console.WriteLine("Hello, World!");



public class MyStringDecoder : MessageToMessageDecoder<IByteBuffer>
{
    protected override void Decode(IChannelHandlerContext ctx, IByteBuffer message, List<object> output)
    {
        // 直接将IByteBuffer转为字符串
        output.Add(message.ToString(Encoding.UTF8));
    }
}